package com.gtt.jr.action.base;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;

import org.apache.log4j.Logger;

import com.gtt.jr.util.JacksonUtils;
import com.opensymphony.xwork2.ModelDriven;

/**
 * Model Action的基类
 * 
 * @author 高甜甜(gao12581@sina.com)
 * @date 2010-8-20
 * 
 */
public abstract class BaseModelAction<T> extends BaseAction implements
		ModelDriven<T> {

	private static final Logger LOGGER = Logger
			.getLogger(BaseModelAction.class);

	private static final long serialVersionUID = -3185610204956377868L;

	public static final String JSON = "json";

	private T model;

	public String getJsonResult() {
		String jsonString = null;
		try {
			jsonString = JacksonUtils.convertToJsonStr(getModel());
		} catch (IOException e) {
			LOGGER.error(e.getMessage());
		}
		return jsonString;
	}

	public T getModel() {
		if (model == null) {
			try {
				model = getModelClass().newInstance();
			} catch (Exception e) {
				LOGGER.error(e.getMessage());
			}
		}
		return model;
	}

	@SuppressWarnings("unchecked")
	private Class<T> getModelClass() {
		return (Class<T>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
	}
}
